package com.korion.andsurfacewallpaperdemo

import android.app.Activity
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PorterDuff
import android.media.MediaPlayer
import android.opengl.GLES20
import android.opengl.GLSurfaceView
import android.os.Bundle
import android.view.Surface
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.ViewTreeObserver
import android.widget.ImageView
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.Toast
import com.korion.andsurfacewallpaperdemo.gl.VideoRenderer
import java.io.IOException
import java.io.InputStream
import androidx.core.graphics.createBitmap

class MainActivity : Activity() {
    private var surfaceViewA: GLSurfaceView? = null // 用于视频播放
    private var surfaceViewB: SurfaceView? = null // 底层SurfaceView
    private var urlEditText: EditText? = null // URL输入框
    private var playButton: ImageView? = null // 播放按钮
    private var mediaPlayer: MediaPlayer? = null
    private var container: FrameLayout? = null // 4:3比例容器
    private var layoutListener: ViewTreeObserver.OnGlobalLayoutListener? = null // 布局监听器
    private var videoRenderer: VideoRenderer? = null // 视频渲染器
    
    // 播放状态枚举
    enum class PlayState {
        IDLE,       // 未播放
        PLAYING,    // 播放中
        PAUSED,     // 暂停中
        COMPLETED   // 播放结束
    }
    
    private var playState = PlayState.IDLE // 当前播放状态

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        initSurfaceViews()
        adjustAspectRatio()
    }

    private fun adjustAspectRatio() {
        container = findViewById(R.id.container)
        
        layoutListener = object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                container?.viewTreeObserver?.removeOnGlobalLayoutListener(this)
                
                // 计算4:3高度 (宽度:高度 = 4:3)
                val width = container?.width ?: 0
                val height = (width * 3) / 4
                
                // 设置容器的高度
                val layoutParams = container?.layoutParams
                layoutParams?.height = height
                container?.layoutParams = layoutParams
            }
        }
        
        container?.viewTreeObserver?.addOnGlobalLayoutListener(layoutListener)
    }

    private fun initSurfaceViews() {
        surfaceViewA = findViewById(R.id.surfaceViewA)
        surfaceViewB = findViewById(R.id.surfaceViewB)
        
        // 设置GLSurfaceView的EGL配置
        surfaceViewA?.setEGLContextClientVersion(2)
        // 设置EGL配置以支持透明度
        surfaceViewA?.setEGLConfigChooser(8, 8, 8, 8, 16, 0)
        surfaceViewA?.holder?.setFormat(android.graphics.PixelFormat.TRANSLUCENT)
        
        surfaceViewA?.setRenderer(object : GLSurfaceView.Renderer {
            override fun onSurfaceCreated(gl: javax.microedition.khronos.opengles.GL10?, config: javax.microedition.khronos.egl.EGLConfig?) {
                // 初始化VideoRenderer
                videoRenderer = VideoRenderer(this@MainActivity)
                videoRenderer?.initGL()
                
                // 将SurfaceTexture设置给MediaPlayer
                val surface = videoRenderer?.getSurfaceTexture()?.let {
                    Surface(it)
                }
                if (surface == null) {
                    runOnUiThread {
                        // 显示错误消息
                        Toast.makeText(this@MainActivity, "无法创建视频表面", Toast.LENGTH_SHORT).show()
                    }
                    return
                }
                mediaPlayer?.setSurface(surface)
            }
            
            override fun onSurfaceChanged(gl: javax.microedition.khronos.opengles.GL10?, width: Int, height: Int) {
                // 设置视口
                GLES20.glViewport(0, 0, width, height)
            }
            
            override fun onDrawFrame(gl: javax.microedition.khronos.opengles.GL10?) {
                // 使用VideoRenderer绘制视频帧
                videoRenderer?.drawFrame(null)
            }
        })
        surfaceViewA?.renderMode = GLSurfaceView.RENDERMODE_CONTINUOUSLY
        urlEditText = findViewById(R.id.urlEditText)
        playButton = findViewById(R.id.playButton)
        
        // 设置播放按钮点击事件
        playButton?.setOnClickListener {
            handlePlayButtonClick()
        }
        
        // 设置初始图片
        playButton?.setImageResource(R.drawable.play)

        // 设置SurfaceView B的Z-order，确保它在SurfaceView A的底层
        surfaceViewB?.setZOrderMediaOverlay(false)
        surfaceViewA?.setZOrderMediaOverlay(true)

        // 移除SurfaceView A的SurfaceHolder回调，因为现在使用GLSurfaceView.Renderer
        // surfaceViewA?.holder?.addCallback(...)

        // 设置SurfaceView B的回调，用于绘制ImageView内容
        surfaceViewB?.holder?.addCallback(object : SurfaceHolder.Callback {
            override fun surfaceCreated(holder: SurfaceHolder) {
                drawImageOnSurfaceB(holder)
            }

            override fun surfaceChanged(
                holder: SurfaceHolder,
                format: Int,
                width: Int,
                height: Int
            ) {
                drawImageOnSurfaceB(holder)
            }

            override fun surfaceDestroyed(holder: SurfaceHolder) {
                // 清理资源
            }
        })
    }

    private fun drawImageOnSurfaceB(holder: SurfaceHolder) {
        var canvas: Canvas? = null
        try {
            canvas = holder.lockCanvas()
            if (canvas != null) {
                // 清空画布
                canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)

                // 从assets目录加载壁纸图片
                var bitmap: Bitmap? = null
                var inputStream: InputStream? = null
                try {
                    inputStream = assets.open("wall_paper.jpg")
                    bitmap = BitmapFactory.decodeStream(inputStream)
                    
                    // 获取SurfaceView B的尺寸
                    val surfaceWidth = canvas.width
                    val surfaceHeight = canvas.height
                    
                    // 创建一个适合SurfaceView B尺寸的缩放Bitmap
                    val scaledBitmap = Bitmap.createScaledBitmap(bitmap!!, surfaceWidth, surfaceHeight, false)
                    
                    // 将缩放后的Bitmap绘制到SurfaceView B的Canvas上，实现铺满效果
                    canvas.drawBitmap(scaledBitmap, 0f, 0f, null)
                    
                    // 回收原来的bitmap
                    bitmap.recycle()
                } catch (e: IOException) {
                    e.printStackTrace()
                    
                    // 如果加载失败，创建一个简单的Bitmap作为示例图像
                    bitmap = createBitmap(200, 200)
                    val bitmapCanvas = Canvas(bitmap)
                    val paint = Paint()
                    paint.color = Color.BLUE
                    paint.style = Paint.Style.FILL
                    bitmapCanvas.drawCircle(100f, 100f, 50f, paint)
                    
                    // 将Bitmap绘制到SurfaceView B的Canvas上
                    canvas.drawBitmap(bitmap, 100f, 100f, null)
                } finally {
                    inputStream?.close()
                }
            }
        } finally {
            if (canvas != null) {
                holder.unlockCanvasAndPost(canvas)
            }
        }
    }

    private fun initMediaPlayer() {
        // 检查SurfaceView A是否已经创建
        if (surfaceViewA == null) {
            return
        }
        
        // 初始化MediaPlayer
        mediaPlayer = MediaPlayer()

        try {
            // 获取输入框中的URL
            val url = urlEditText?.text.toString()
            
            // 设置视频源（使用输入框中的URL）
            // 在实际应用中，您可能需要处理权限和网络访问
            mediaPlayer!!.setDataSource(url)

            // 将SurfaceTexture设置给MediaPlayer
            val surface = videoRenderer?.getSurfaceTexture()?.let {
                Surface(it)
            }
            if (surface == null) {
                runOnUiThread {
                    // 显示错误消息
                    Toast.makeText(this@MainActivity, "无法创建视频表面", Toast.LENGTH_SHORT).show()
                }
                return
            }
            // 设置SurfaceTexture作为视频输出
            mediaPlayer!!.setSurface(surface)

            // 异步准备视频
            mediaPlayer!!.prepareAsync()

            // 设置准备完成的监听器
            mediaPlayer!!.setOnPreparedListener { 
                // 开始播放视频
                mediaPlayer!!.start()
                playState = PlayState.PLAYING
            }
            
            // 设置播放完成的监听器
            mediaPlayer!!.setOnCompletionListener {
                playState = PlayState.COMPLETED
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        
        // 移除ViewTreeObserver监听器
        if (layoutListener != null && container != null) {
            container?.viewTreeObserver?.removeOnGlobalLayoutListener(layoutListener)
        }
        
        if (mediaPlayer != null) {
            mediaPlayer!!.release()
            mediaPlayer = null
        }
        
        // 释放VideoRenderer资源
        videoRenderer?.release()
        videoRenderer = null
    }
    
    /**
     * 处理播放按钮点击事件
     */
    private fun handlePlayButtonClick() {
        when (playState) {
            PlayState.IDLE -> {
                // 未播放 -> 点击播放
                initMediaPlayer()
                // 设置半透明效果
                videoRenderer?.setAlpha(0.5f)
            }
            PlayState.PLAYING -> {
                // 播放中 -> 点击暂停
                mediaPlayer?.pause()
                playState = PlayState.PAUSED
            }
            PlayState.PAUSED -> {
                // 暂停中 -> 点击继续播放
                mediaPlayer?.start()
                playState = PlayState.PLAYING
            }
            PlayState.COMPLETED -> {
                // 播放结束 -> 点击重新播放
                mediaPlayer?.seekTo(0)
                mediaPlayer?.start()
                playState = PlayState.PLAYING
            }
        }
        // 统一更新按钮文本和请求重绘
        updatePlayButtonText()
        surfaceViewA?.requestRender()
    }
    
    /**
     * 更新播放按钮图片
     */
    private fun updatePlayButtonText() {
        when (playState) {
            PlayState.IDLE -> playButton?.setImageResource(R.drawable.play)
            PlayState.PLAYING -> playButton?.setImageResource(R.drawable.pause)
            PlayState.PAUSED -> playButton?.setImageResource(R.drawable.play)
            PlayState.COMPLETED -> playButton?.setImageResource(R.drawable.play)
        }
    }
}